/* 
 * Copyright (C) 2001-2003 Jacek Sieka, j_s@telia.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "stdinc.h"
#include "DCPlusPlus.h"

#include "SettingsManager.h"
#include "ResourceManager.h"

#include "SimpleXML.h"
#include "Util.h"
#include "File.h"
#include "HubManager.h"

const string SettingsManager::settingTags[] =
{
	// Strings
	"Connection", "Description", "DownloadDirectory", "EMail", "Nick", "Server",
	"ClientVersion", "Font", "MainFrameOrder", "MainFrameWidths", "HubFrameOrder", "HubFrameWidths", 
	"LanguageFile", "SearchFrameOrder", "SearchFrameWidths", "FavoritesFrameOrder", "FavoritesFrameWidths", 
	"HublistServers", "QueueFrameOrder", "QueueFrameWidths", "PublicHubsFrameOrder", "PublicHubsFrameWidths", 
	"UsersFrameOrder", "UsersFrameWidths", "HttpProxy", "LogDirectory", "NotepadText", "LogFormatPostDownload",
	"LogFormatPostUpload", "LogFormatMainChat", "LogFormatPrivateChat", "FinishedOrder", "FinishedWidths",	
	"TempDownloadDirectory", "SocksServer", "SocksUser", "SocksPassword", "ConfigVersion",
	"DefaultAwayMessage", "ADLSearchFrameOrder", "ADLSearchFrameWidths", 
	"FinishedULWidths", "FinishedULOrder",
	"BeepFile", "SearchServer",
	"WinampFormat", "MplayercFormat", "ItunesFormat",
	// CDM EXTENSION BEGINS
	"UpdateURL", "KickMsgRecent01", "KickMsgRecent02", "KickMsgRecent03", "KickMsgRecent04", "KickMsgRecent05", 
	"KickMsgRecent06", "KickMsgRecent07", "KickMsgRecent08", "KickMsgRecent09", "KickMsgRecent10", 
	"KickMsgRecent11", "KickMsgRecent12", "KickMsgRecent13", "KickMsgRecent14", "KickMsgRecent15", 
	"KickMsgRecent16", "KickMsgRecent17", "KickMsgRecent18", "KickMsgRecent19", "KickMsgRecent20",
	"UpdateISPURL", "ProtectedUsers", "ClipboardNameOne", "ClipboardNameTwo", "ClipboardNameThree", 
	"ClipboardNameFour", "ClipboardNameFive", "ClipboardNameSix", "ClipboardTextOne", "ClipboardTextTwo", 
	"ClipboardTextThree", "ClipboardTextFour", "ClipboardTextFive", "ClipboardTextSix",
	"LogFormatPostRawCommands", "LastScript", "ScriptFont", "WinampLocation", "BackgroundImage",
	// CDM EXTENSION ENDS
	"CvFrameOrder", "CvFrameWidths", "ClientVersionSite", "MainFrameVisible", "SearchFrameVisible", 
	"HubFrameVisible","ReportFont","UpdateMyinfos", "Silentline", "Removeline", "DCDMUpdateLastCheck",
	"SENTRY", 
	// Ints
	"ConnectionType", "InPort", "Slots", "Rollback", "AutoFollow", "ClearSearch", "FullRow",
	"BackgroundColor", "TextColor", "UseOemMonoFont", "ShareHidden", "MinimizeToTray",
	"OpenPublic", "OpenQueue", "AutoSearch", "AutoAutoSearchString", "TimeStamps", "ConfirmExit", "IgnoreOffline", "PopupOffline",
	"ListDuplicates", "BufferSize", "DownloadSlots", "MaxDownloadSpeed", "LogMainChat", "LogPrivateChat",
	"LogDownloads", "LogUploads", "StatusInChat", "ShowJoins", "PrivateMessageBeep", "PrivateMessageBeepOpen",
	"UseSystemIcons", "PopupPMs", "MinUploadSpeed", "GetUserInfo", "UrlHandler", "MainWindowState", 
	"MainWindowSizeX", "MainWindowSizeY", "MainWindowPosX", "MainWindowPosY", "AutoAway",
	"SmallSendBuffer", "SocksPort", "SocksResolve", "KeepLists", "AutoKick", "QueueFrameShowTree",
	"CompressTransfers", "ShowProgressBars", "SFVCheck", "MaxTabRows", "AutoUpdateList",
	"MaxCompression", "FinishedDirty", "QueueDirty", "AntiFrag", "MDIMaxmimized", "NoAwayMsgToBots",
	"SkipZeroByte", "AdlsBreakOnFirst", "TabCompletion", "OpenFavoriteHubs", "OpenFinishedDownloads",
	"MaxUploadSpeed", "MaxDownloadSpeedReal",
	"HubIPSet", "SmallFileSize", "SearchInPort", "ThrottleEnabled",
	"BandwidthLimitStart", "BandwidthLimitEnd", "TimeDependentThrottle", "MaxDownloadSpeedRealTime",
	"MaxUploadSpeedTime", "EvilHiddenSetting", "YetAnotherEvilHiddenSetting", "PartialUploadLogging",
	"UseUnderlineAsBoldFont", "BlockVersionPopups", "ZoneAlarmDetections", "RememberUploads", 
	"The_Ducklings_Are_Coming_Run_Run_Hide", "They_Are_Nasty_Fuckers_Are_They_Not",
	"HubUserCommands", "AutoSearchAutoMatch", "DownloadBarColor", "UploadBarColor", "LogSystem",
	"LogFilelistTransfers", "AutoSearchExact", "SendUnknownCommands",
	// CDM EXTENSION BEGINS
	"DownloadUploadRatio", "DownloadUploadRatioTime", "PercentFakeShareTolerated", "FakeRaw",
	"MinimumFileListSize", "MaximumFileListSize", "DebugCommands", "DebugDetection", 
	"NormalColour", "ClientCheckedNotFilelistColour", "FileListCheckedNotClientColour", 
	"FileListAndClientCheckedColour", "BadClientColour", "BadFilelistColour", "FavShowJoins", "MaxTestSURs",
	"MaxFileLists", "CheckDelay", "FloodCounter", "FloodTime", "FloodNotify", "FloodKick", "ExtendedChecking",
	"ConsiderCZDCBCDCCheat", "ISPChecking", "CheckAllClientsBeforeFilelists", "AutomaticallyCheckHubCounts",
	"CheckSmallFiles", "DisconnectRaw", "TimeoutRaw", "AcceptedDisconnects", "AcceptedTimeouts", "UserListImages",
	"HideDCDMTag", "NoSlotsDcpp", "FileListTooBig", "FileListTooSmall", "FileListUnavailable", "SmallFileError",
	"ListLenMismatch", "ListLenEleven", "VersionMismatch", "DisplayCheatsInMainChat", "UseVerticalView",
	"DeleteCheckedFilelists", "LogRawCommands", "KeywordColour", "QuoteColour", "CommentColour", "ScriptBackground",
	"ScriptNormalColour", "LibraryColour", "OperatorColour", "BadIsp", "CheckConflicts", "TabWholeNick",
	"SleepTime", "MatchShareHubCount", "MatchShareMultiHub", "ShowIPs", "ShowWinampControl", "ReverseConnect",
	"VerUserListWidth", "HorUserListWidth", "HashErrorRaw", "PercentHashed", "CheckHash",
	// CDM EXTENSION ENDS
	// SVN Extension starts
	"DefaultSearchFreeSlots", "PopunderPm", "PopunderFilelist", "SearchHistory", "SendUseripOnConnect", "ShowLastLinesLog", 
	"MaxHashSpeed", "SendReportToPm", "UserSpecificTimeOut", "DownloadLimitEnable", "MinDownSpeed", "HDownSpeed", 
	"DownTime", "MinFileSize", "RemoveSlowUser", "NumOnlineUsers", "PopunderAlert", "TagFilelistGenMismatch", "ProtectFavourites",
	"Refresh_Every_Hours", "ADL_Failed_Hours", "rmDC", "ExtendedChecking2", "AdlRawLowPoints", "AdlRawMediumPoints", "AdlRawHighPoints",
	"ProtectedColour", "FakeFileListRaw","UseVersionChecker",
	"UseDirlistVerticalView", "NormalColourBg", "ClientCheckedNotFilelistColourBg", "FileListCheckedNotClientColourBg", 
	"FileListAndClientCheckedColourBg", "BadClientColourBg", "BadFilelistColourBg", "ProtectedColourBg",
	"UsePmFormattingScript", "SendConnectToMeAfterAddingTestSUR", "AlertOnClientUpdates", "GetUserCountry",
	"GetUserCountryPm", "ShowIpsPm", "OnlineOfflinePm", 
	"DisplayDisconnectCheat", "DisplayTimeoutCheat", "DisplayNoSlotsDcppCheat", "DisplayFilelistTooBigCheat", 
	"DisplayFilelistTooSmallCheat", "DisplayFilelistUnavailableCheat", "DisplaySmallFileErrorCheat", 
	"DisplayListlenMismatchCheat", "DisplayListlenElevenCheat", "DisplayVersionMismatchCheat", "DisplayBadIspCheat", 
	"DisplayReverseConnectCheat", "DisplayRmdcCheat", "DisplayDivisibleBy1MBCheat", 
	"DisplayTooManySameNumbersCheat", "RecheckAfterListlist11B", "ToManyIpsRaw",
	"DisplayToManyIpsCheat", "MaxConnections" ,	"YouReallyDoNotWantToEnableThis", "CheckMaxIpPerHub", 
	"TokenForCheatDescription", "InflatedFilelistRaw", "DisplayInflatedFilelistCheat", "UseUpnp", "NoIpOverride",
	"DivisibleBy1MBRaw", "TooManySameNumbersRaw", "MaxSearchHits", "OpenNotepadStatup", "SaveNotepadTime",
	"RefreshFilelistOnStartup", "CheckNickSpoofing", "DisplayActiveUsingPassive", "ActiveUsingPassiveRaw",
	// end
	"SENTRY",
	"TotalUpload", "TotalDownload", "ItunesOffset",
	// CDM EXTENSION BEGINS
	"TotalDetects", "TotalFailedDetects", "TotalRawCommandsSent",
	// CDM EXTENSION ENDS
	"SENTRY"
};

const string SettingsManager::connectionSpeeds[] = { "28.8Kbps", "33.6Kbps", "56Kbps", "ISDN", 
"Satellite", "Cable", "DSL", "LAN(T1)", "LAN(T3)" };

SettingsManager::SettingsManager()
{
	for(int i=0; i<SETTINGS_LAST; i++)
		isSet[i] = false;

	for(int j=0; j<INT_LAST-INT_FIRST; j++) {
		intDefaults[j] = 0;
		intSettings[j] = 0;
	}
	for(int k=0; k<INT64_LAST-INT64_FIRST; k++) {
		int64Defaults[k] = 0;
		int64Settings[k] = 0;
	}
	
	setDefault(DOWNLOAD_DIRECTORY, Util::getAppPath() + "Downloads\\");
	setDefault(SLOTS, 1);
	setDefault(SERVER, Util::getLocalIp());
	setDefault(SEARCH_SERVER, Util::emptyString);
	setDefault(IN_PORT, Util::rand(1025, 32000));
	setDefault(SEARCH_IN_PORT, 0);
	setDefault(ROLLBACK, 32768);
	setDefault(CLIENTVERSION, "1,0091");
	setDefault(AUTO_FOLLOW, false);
	setDefault(CLEAR_SEARCH, true);
	setDefault(FULL_ROW_SELECT, true);
	setDefault(SHARE_HIDDEN, false);
	setDefault(MINIMIZE_TRAY, false);
	setDefault(OPEN_PUBLIC, false);
	setDefault(OPEN_QUEUE, false);
	setDefault(AUTO_SEARCH, false);
	setDefault(AUTO_SEARCH_AUTO_STRING, false);
	setDefault(TIME_STAMPS, true);
	setDefault(CONFIRM_EXIT, false);
	setDefault(IGNORE_OFFLINE, false);
	setDefault(POPUP_OFFLINE, false);
	setDefault(LIST_DUPES, false);
	setDefault(BUFFER_SIZE, 64);
	setDefault(HUBLIST_SERVERS, "http://www.hublist.org/PublicHubList.config.bz2");
	setDefault(DOWNLOAD_SLOTS, 3);
	setDefault(MAX_DOWNLOAD_SPEED, 0);
	setDefault(LOG_DIRECTORY, Util::getAppPath() + "Logs\\");
	setDefault(LOG_UPLOADS, true);
	setDefault(LOG_DOWNLOADS, false);
	setDefault(LOG_PRIVATE_CHAT, true);
	setDefault(LOG_MAIN_CHAT, false);
	setDefault(STATUS_IN_CHAT, true);
	setDefault(SHOW_JOINS, false);
	setDefault(CONNECTION, connectionSpeeds[0]);
	setDefault(PRIVATE_MESSAGE_BEEP, false);
	setDefault(PRIVATE_MESSAGE_BEEP_OPEN, false);
	setDefault(USE_SYSTEM_ICONS, true);
	setDefault(USE_OEM_MONOFONT, false);
	setDefault(POPUP_PMS, true);
	setDefault(MIN_UPLOAD_SPEED, 0);
	setDefault(LOG_FORMAT_POST_DOWNLOAD, "%Y-%m-%d %H:%M: %[target]" + STRING(DOWNLOADED_FROM) + "%[user], %[size] (%[chunksize]), %[speed], %[time]");
	setDefault(LOG_FORMAT_POST_UPLOAD, "%Y-%m-%d %H:%M: %[source]" + STRING(UPLOADED_TO) + "%[user], %[size] (%[chunksize]), %[speed], %[time]");
	setDefault(LOG_FORMAT_MAIN_CHAT, "[%Y-%m-%d %H:%M] %[message]");
	setDefault(LOG_FORMAT_PRIVATE_CHAT, "[%Y-%m-%d %H:%M] %[message]");
	setDefault(GET_USER_INFO, true);
	setDefault(URL_HANDLER, false);
	setDefault(AUTO_AWAY, false);
	setDefault(SMALL_SEND_BUFFER, false);
	setDefault(SOCKS_PORT, 1080);
	setDefault(SOCKS_RESOLVE, 1);
	setDefault(CONFIG_VERSION, "0.181");		// 0.181 is the last version missing configversion
	setDefault(KEEP_LISTS, false);
	setDefault(AUTO_KICK, true);
	setDefault(QUEUEFRAME_SHOW_TREE, true);
	setDefault(COMPRESS_TRANSFERS, true);
	setDefault(SHOW_PROGRESS_BARS, true);
	setDefault(SFV_CHECK, true);
	setDefault(DEFAULT_AWAY_MESSAGE, "I'm away. I might answer later if you're lucky.");
	setDefault(MAX_TAB_ROWS, 2);
	setDefault(AUTO_UPDATE_LIST, true);
	setDefault(MAX_COMPRESSION, 6);
	setDefault(FINISHED_DIRTY, true);
	setDefault(QUEUE_DIRTY, true);
	setDefault(ANTI_FRAG, false);
	setDefault(NO_AWAYMSG_TO_BOTS, true);
	setDefault(SKIP_ZERO_BYTE, false);
	setDefault(ADLS_BREAK_ON_FIRST, false);
	setDefault(TAB_COMPLETION, true);
	setDefault(OPEN_FAVORITE_HUBS, false);
	setDefault(OPEN_FINISHED_DOWNLOADS, false);
	setDefault(MAX_UPLOAD_SPEED, 0);
	setDefault(HUB_IP_SET, true);
	setDefault(SMALL_FILE_SIZE, 128);
	setDefault(THROTTLE_ENABLE, true);
	setDefault(TIME_DEPENDENT_THROTTLE, false);
	setDefault(MAX_DOWNLOAD_SPEED_REAL_TIME, 0);
	setDefault(MAX_UPLOAD_SPEED_TIME, 0);
	setDefault(BANDWIDTH_LIMIT_START, 0);
	setDefault(BANDWIDTH_LIMIT_END, 0);
	setDefault(PARTIAL_UPLOAD_LOGGING, false);
	//setDefault(OPEN_UPLOAD_QUEUE, false);
	//setDefault(UPLOAD_QUEUE_EXPAND, true);
	setDefault(WINAMP_FORMAT, "winamp(%[version]) %[state] (%[title]) stats(%[percent] of %[length] %[bar])");
	setDefault(MPLAYERC_FORMAT, "Media Player Classic %[version] %[state] %[filename] %[size] (%[elapsed]/%[length])");
	setDefault(ITUNES_FORMAT, "iTunes: artist: %[artist] - title: %[title] - file: %[filename] - album: %[album] - year: %[year] - length: %[length] - size: %[size] - bitrate: %[bitrate] - frequency: %[frequency]");
	setDefault(ITUNES_OFFSET, 0);
	setDefault(USE_UNDERLINE_AS_BOLD_FONT, true);
	setDefault(BLOCK_VERSION_POPUPS, false);
	setDefault(ZONEALARM_DETECTIONS, 0);
	setDefault(HUB_USER_COMMANDS, true);
	setDefault(AUTO_SEARCH_AUTO_MATCH, true);
	setDefault(LOG_FILELIST_TRANSFERS, true);
	setDefault(REMEMBER_UPLOADS, true);
	setDefault(AUTO_SEARCH_EXACT, true);
	setDefault(LOG_SYSTEM, false);
	setDefault(SEND_UNKNOWN_COMMANDS, true);
	// CDM EXTENSION BEGINS
	setDefault(DOWNLOAD_UPLOAD_RATIO, 1);
	setDefault(DOWNLOAD_UPLOAD_RATIO_TIME, 1);
	setDefault(PERCENT_FAKE_SHARE_TOLERATED, 10);
	setDefault(FAKE_RAW, 0);
	setDefault(MINIMUM_FILELIST_SIZE, 100);
	setDefault(MAXIMUM_FILELIST_SIZE, 10*1024*1024);
	setDefault(DEBUG_COMMANDS, true);
	setDefault(DEBUG_DETECTION, false);
	setDefault(UPDATE_URL, GETVERSION);
	setDefault(NORMAL_COLOUR, 0);
	setDefault(CLIENT_CHECKED_NOT_FILELIST_COLOUR, 32768);
	setDefault(FILELIST_CHECKED_NOT_CLIENT_COLOUR, 8421440);
	setDefault(FILELIST_AND_CLIENT_CHECKED_COLOUR, 65280);
	setDefault(BAD_CLIENT_COLOUR, 255);
	setDefault(BAD_FILELIST_COLOUR, 8388863);
	setDefault(FAV_SHOW_JOINS, false);
	setDefault(MAX_TESTSURS, 20);
	setDefault(MAX_FILELISTS, 5);
	setDefault(CHECK_DELAY, 5000);
	setDefault(KICK_MSG_RECENT_01, "");
	setDefault(KICK_MSG_RECENT_02, "");
	setDefault(KICK_MSG_RECENT_03, "");
	setDefault(KICK_MSG_RECENT_04, "");
	setDefault(KICK_MSG_RECENT_05, "");
	setDefault(KICK_MSG_RECENT_06, "");
	setDefault(KICK_MSG_RECENT_07, "");
	setDefault(KICK_MSG_RECENT_08, "");
	setDefault(KICK_MSG_RECENT_09, "");
	setDefault(KICK_MSG_RECENT_10, "");
	setDefault(KICK_MSG_RECENT_11, "");
	setDefault(KICK_MSG_RECENT_12, "");
	setDefault(KICK_MSG_RECENT_13, "");
	setDefault(KICK_MSG_RECENT_14, "");
	setDefault(KICK_MSG_RECENT_15, "");
	setDefault(KICK_MSG_RECENT_16, "");
	setDefault(KICK_MSG_RECENT_17, "");
	setDefault(KICK_MSG_RECENT_18, "");
	setDefault(KICK_MSG_RECENT_19, "");
	setDefault(KICK_MSG_RECENT_20, "");
	setDefault(FLOOD_COUNTER, 5);
	setDefault(FLOOD_TIME, 1000);
	setDefault(FLOOD_NOTIFY, true);
	setDefault(FLOOD_KICK, false);
	setDefault(EXTENDED_CHECKING, false);
	setDefault(CONSIDER_CZDCBCDC_CHEAT, false);
	setDefault(ISP_CHECKING, true);
	// Flow84 changes svn82
	//setDefault(UPDATE_ISP_URL, "http://www.bostream.nu/sulan/isp/");
	setDefault(UPDATE_ISP_URL, UPDATE_ISP);
	// Flow84 end
	setDefault(CHECK_ALL_CLIENTS_BEFORE_FILELISTS, true);
	setDefault(CLIPBOARD_NAME_ONE, "Tag");
	setDefault(CLIPBOARD_NAME_TWO, "Lock");
	setDefault(CLIPBOARD_NAME_THREE, "Pk");
	setDefault(CLIPBOARD_NAME_FOUR, "Supports");
	setDefault(CLIPBOARD_NAME_FIVE, "TestSUR");
	setDefault(CLIPBOARD_NAME_SIX, "CD");
	setDefault(CLIPBOARD_TEXT_ONE, "^<\\+\\+ V:%[version],M:([AP5]){1},H:([0-9]){1,3}/([0-9]){1,3}/([0-9]){1,3}(,S:([0-9]){1,3}|,S:([0-9]){1,3},O:([0-9]){1,10})>$");
	setDefault(CLIPBOARD_TEXT_TWO, "^EXTENDEDPROTOCOLABCABCABCABCABCABC$");
	setDefault(CLIPBOARD_TEXT_THREE, "^DCPLUSPLUS%[version]ABCABC$");
	setDefault(CLIPBOARD_TEXT_FOUR, "BZList MiniSlots XmlBZList GetTestZBlock GetZBlock ADCGet TTHL ZLIG CHUNK ");
	setDefault(CLIPBOARD_TEXT_FIVE, "File Not Available");
	setDefault(CLIPBOARD_TEXT_SIX, "Your client is not allowed in this hub.");
	setDefault(AUTOMATICALLY_CHECK_HUB_COUNTS, true);
	setDefault(CHECK_SMALL_FILES, true);
	setDefault(DISCONNECT_RAW, 0);
	setDefault(TIMEOUT_RAW, 0);
	setDefault(ACCEPTED_DISCONNECTS, 5);
	setDefault(ACCEPTED_TIMEOUTS, 10);
	setDefault(USER_LIST_IMAGES, 0);
	setDefault(HIDE_DCDM_TAG, false);
	setDefault(NO_SLOTS_DCPP, 0);
	setDefault(FILELIST_TOO_BIG, 0);
	setDefault(FILELIST_TOO_SMALL, 0);
	setDefault(FILELIST_UNAVAILABLE, 0);
	setDefault(SMALL_FILE_ERROR, 0);
	setDefault(LISTLEN_MISMATCH, 0);
	setDefault(LISTLEN_ELEVEN, 0);
	setDefault(VERSION_MISMATCH, 0);
	setDefault(DISPLAY_CHEATS_IN_MAIN_CHAT, true);
	setDefault(USE_VERTICAL_VIEW, true);
	setDefault(DELETE_CHECKED_FILELISTS, false);
	setDefault(LOG_FORMAT_POST_RAW_COMMANDS, "%[nick] %[cd]");
	setDefault(LOG_RAW_COMMANDS, false);
	setDefault(KEYWORD_COLOUR, 16711680);
	setDefault(QUOTE_COLOUR, 16711935);
	setDefault(COMMENT_COLOUR, 32768);
	setDefault(LIBRARY_COLOUR, 255);
	setDefault(OPERATOR_COLOUR, 8421376);
	setDefault(SCRIPT_NORMAL_COLOUR, 0);
	setDefault(SCRIPT_BACKGROUND_COLOUR, 16777215);
	setDefault(BAD_ISP, 0);
	setDefault(CHECK_CONFLICTS, false);
	setDefault(TAB_WHOLE_NICK, false);
	setDefault(WINAMP_LOCATION, "C:\\Program Files\\Winamp\\");
	setDefault(SLEEP_TIME, 1000);
	setDefault(BACKGROUND_IMAGE, "images\\nebula.jpg");
	setDefault(MATCH_SHARE_SIZE_FOR_FAKE_HUB_COUNTS, true);
	setDefault(MATCH_SHARE_SIZE_FOR_MULTI_HUB_KICK, true);
	setDefault(SHOW_IPS, false);
	setDefault(REVERSE_CONNECT, 0);
	setDefault(VERTICAL_USER_LIST_WIDTH, 7500);
	setDefault(HORIZONTAL_USER_LIST_WIDTH, 2500);
	setDefault(HASH_ERROR_RAW, 0);
	setDefault(PERCENT_HASHED, 10);
	setDefault(CHECK_HASH, false);
	// CDM EXTENSION ENDS
	// pothead starts
	setDefault(FREE_SLOTS_DEFAULT, false);
	setDefault(POPUNDER_PM, true);
	setDefault(POPUNDER_FILELIST, true);
	setDefault(SEARCH_HISTORY, 10);
	setDefault(SEND_USERIP_ON_CONNECT, false);
	setDefault(SHOW_LAST_LINES_LOG, 5);
	setDefault(MAX_HASH_SPEED, 10);
	setDefault(SEND_REPORT_TO_PM, false);
	setDefault(USER_SPECIFIC_TIME_OUT, false);
	setDefault(DOWNLOAD_LIMIT_ENABLE, false);
	setDefault(MIN_DOWN_SPEED, 0);
	setDefault(DOWN_TIME, 1);
	setDefault(H_DOWN_SPEED, 0);
	setDefault(MIN_FILE_SIZE, 10);
	setDefault(NUM_ONLINE_USERS, 5);
	setDefault(REMOVE_SLOW_USER, 1);
	setDefault(POPUNDER_ALERT, false);
	setDefault(TAG_FILELIST_GEN_MISMATCH, 0);
	setDefault(PROTECT_FAVOURITES, true);
	setDefault(REFRESH_EVERY_HOURS, 1);
	setDefault(ADL_FAIL_HOURS, 0);
	setDefault(RMDC, 0);
	setDefault(UPDATE_MYINFOS, UPDATE_MYINFO);
	setDefault(EXTENDED_CHECKING2, false);
	setDefault(ADL_RAW_LOW_POINTS, 0);
	setDefault(ADL_RAW_MEDIUM_POINTS, 0);
	setDefault(ADL_RAW_HIGH_POINTS, 0);
	setDefault(DISPLAY_DISCONNECT_CHEAT, true);
	setDefault(DISPLAY_TIMEOUT_CHEAT, true);
	setDefault(DISPLAY_NO_SLOTS_DCPP_CHEAT, true);
	setDefault(DISPLAY_FILELIST_TOO_BIG_CHEAT, true);
	setDefault(DISPLAY_FILELIST_TOO_SMALL_CHEAT, true);
	setDefault(DISPLAY_FILELIST_UNAVAILABLE_CHEAT, true);
	setDefault(DISPLAY_SMALL_FILE_ERROR_CHEAT, true);
	setDefault(DISPLAY_LISTLEN_MISMATCH_CHEAT, true);
	setDefault(DISPLAY_LISTLEN_ELEVEN_CHEAT, true);
	setDefault(DISPLAY_VERSION_MISMATCH_CHEAT, true);
	setDefault(DISPLAY_BAD_ISP_CHEAT, true);
	setDefault(DISPLAY_REVERSE_CONNECT_CHEAT, true);
	setDefault(DISPLAY_RMDC_CHEAT, true);
	setDefault(DISPLAY_TO_MANY_IPS_CHEAT, true);
	setDefault(DISPLAY_INFLATED_FILELIST_CHEAT, true);
	setDefault(DISPLAY_DIVISIBLE_BY_1MB_CHEAT, true);
	setDefault(DISPLAY_TOO_MANY_OF_SAME_NUMBERS_CHEAT, true);
	setDefault(DISPLAY_ACTIVE_USING_PASSIVE, true);
	setDefault(GET_USER_COUNTRY_PM, false);
	setDefault(SHOW_IPS_PM, false);
	setDefault(ONLINE_OFFLINE_PM, true);
	setDefault(RECHECK_LISTLEN_11B_FAILED_AFTER_FILELIST, true);
	setDefault(CRASH_ON_CONNECTED_TO_A_HUB, false);
	setDefault(CHECK_MAX_IPS_PER_HUB, false);
	setDefault(TOKEN_FOR_CHEAT_STRING, 0);
	setDefault(INFLATED_FILELIST_RAW, 0);
	setDefault(DIVISIBLE_BY_1MB_RAW, 0);
	setDefault(TOO_MANY_OF_SAME_NUMBERS_RAW, 0);
	setDefault(MAX_SEARCH_HITS, 0);
	setDefault(OPEN_NOTEPAD, false);
	setDefault(DCDMUPDATE_LASTCHECK, "never");
	setDefault(CHECK_NICK_SPOOFING, true);
	setDefault(ACTIVE_USING_PASSIVE_RAW, 0);
	// pothead ends
	//Sulans start
	setDefault(PROTECTED_COLOUR, RGB(0,0,250));
	setDefault(USE_VERSION_CHECKER, true);
	setDefault(CLIENT_VERSION_SITE, GETVERSION);
	setDefault(USE_DIRLIST_VERTICAL_VIEW, true);
	setDefault(NORMAL_COLOUR_BG, -1);
	setDefault(CLIENT_CHECKED_NOT_FILELIST_COLOUR_BG, -1);
	setDefault(FILELIST_CHECKED_NOT_CLIENT_COLOUR_BG, -1); 
	setDefault(FILELIST_AND_CLIENT_CHECKED_COLOUR_BG, -1); 
	setDefault(BAD_CLIENT_COLOUR_BG, -1); 
	setDefault(BAD_FILELIST_COLOUR_BG, -1); 
	setDefault(PROTECTED_COLOUR_BG, -1);
	setDefault(HUBFRAME_VISIBLE, "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1");
	setDefault(USE_PM_FORMATTING_SCRIPT, false);
	setDefault(SEND_CONNECT_TO_ME_AFTER_ADDING_TESTSUR, false);
	setDefault(ALERT_ON_CLIENT_UPDATES, false);
	setDefault(TO_MANY_IPS_RAW, 0);
	setDefault(DISPLAY_TO_MANY_IPS_CHEAT, false);
	setDefault(MAX_CONNECTION_SETTING, 10);
	setDefault(NO_IP_OVERRIDE, false);
	setDefault(USE_UPNP, false);
	//End
	// Flow starts
	setDefault(GET_USER_COUNTRY, false);
	// Flow ends
	// CraKteR start svn?, svn52
	setDefault(SAVE_NOTEPAD_TIME, 0);
	setDefault(REFRESH_FILELIST_ON_STARTUP, true);
	// CraKteR end
	//Gabberworld new_svn 36 (R2 013)
	setDefault(SILENTLINE, "");
	setDefault(REMOVELINE, "");
	//end new_svn 36
#ifdef _WIN32
	setDefault(MAIN_WINDOW_STATE, SW_SHOWNORMAL);
	setDefault(MAIN_WINDOW_SIZE_X, CW_USEDEFAULT);
	setDefault(MAIN_WINDOW_SIZE_Y, CW_USEDEFAULT);
	setDefault(MAIN_WINDOW_POS_X, CW_USEDEFAULT);
	setDefault(MAIN_WINDOW_POS_Y, CW_USEDEFAULT);
	setDefault(MDI_MAXIMIZED, true);
	setDefault(UPLOAD_BAR_COLOR, RGB(205, 60, 55));
	setDefault(DOWNLOAD_BAR_COLOR, RGB(55, 170, 85));

#endif
}

void SettingsManager::load(string const& aFileName)
{
	string xmltext;
	try {
		File f(aFileName, File::READ, File::OPEN);
		xmltext = f.read();		
	} catch(const FileException&) {
		// ...
		return;
	}

	if(xmltext.empty()) {
		// Nothing to load...
		return;
	}

	try {
		SimpleXML xml;
		xml.fromXML(xmltext);
		
		xml.resetCurrentChild();
		
		xml.stepIn();
		
		if(xml.findChild("Settings"))
		{
			xml.stepIn();
			
			int i;
			string attr;
			
			for(i=STR_FIRST; i<STR_LAST; i++)
			{
				attr = settingTags[i];
				dcassert(attr.find("SENTRY") == string::npos);
				
				if(xml.findChild(attr))
					set(StrSetting(i), xml.getChildData());
				xml.resetCurrentChild();
			}
			for(i=INT_FIRST; i<INT_LAST; i++)
			{
				attr = settingTags[i];
				dcassert(attr.find("SENTRY") == string::npos);
				
				if(xml.findChild(attr))
					set(IntSetting(i), Util::toInt(xml.getChildData()));
				xml.resetCurrentChild();
			}
			for(i=INT64_FIRST; i<INT64_LAST; i++)
			{
				attr = settingTags[i];
				dcassert(attr.find("SENTRY") == string::npos);
				
				if(xml.findChild(attr))
					set(Int64Setting(i), Util::toInt64(xml.getChildData()));
				xml.resetCurrentChild();
			}
			
			xml.stepOut();
		}
		string pothead_addy = POTHEADPAGE;
		string flow_addy = FLOWPAGE "files/DCDM/xml/";
		if(get(UPDATE_ISP_URL) == flow_addy) { set(UPDATE_ISP_URL, pothead_addy); }
		if(get(CLIENT_VERSION_SITE) == flow_addy) { set(CLIENT_VERSION_SITE, pothead_addy); }
		if(get(UPDATE_URL) == flow_addy) { set(UPDATE_URL, pothead_addy); }
		if(get(UPDATE_MYINFOS) == flow_addy) { set(UPDATE_MYINFOS, pothead_addy); }

		fire(SettingsManagerListener::Load(), &xml);

		xml.stepOut();

	} catch(const Exception&) {
		// Oops, bad...
	}
}

void SettingsManager::save(string const& aFileName) {

	SimpleXML xml;
	xml.addTag("DCPlusPlus");
	xml.stepIn();
	xml.addTag("Settings");
	xml.stepIn();

	int i;
	string type("type"), curType("string");
	
	for(i=STR_FIRST; i<STR_LAST; i++)
	{
		if(i == CONFIG_VERSION) {
			xml.addTag(settingTags[i], VERSIONSTRING);
			xml.addChildAttrib(type, curType);
		} else if(isSet[i]) {
			xml.addTag(settingTags[i], get(StrSetting(i), false));
			xml.addChildAttrib(type, curType);
		}
	}

	curType = "int";
	for(i=INT_FIRST; i<INT_LAST; i++)
	{
		if(isSet[i]) {
			xml.addTag(settingTags[i], get(IntSetting(i), false));
			xml.addChildAttrib(type, curType);
		}
	}
	curType = "int64";
	for(i=INT64_FIRST; i<INT64_LAST; i++)
	{
		if(isSet[i])
		{
			xml.addTag(settingTags[i], get(Int64Setting(i), false));
			xml.addChildAttrib(type, curType);
		}
	}
	xml.stepOut();
	
	fire(SettingsManagerListener::Save(), &xml);

	try {
		File out(aFileName + ".tmp", File::WRITE, File::CREATE | File::TRUNCATE);
		BufferedOutputStream<false> f(&out);
		f.write(SimpleXML::w1252Header);
		xml.toXML(&f);
		f.flush();
		out.close();
		File::deleteFile(aFileName);
		File::renameFile(aFileName + ".tmp", aFileName);
	} catch(const FileException&) {
		// ...
	}
}

// pothead extension starts (r2 code) #7
string SettingsManager::getDownloadDir(string ext){
	return SETTING(DOWNLOAD_DIRECTORY);
}
// pothead extension ends (r2 code)

bool SettingsManager::getType(const string& name, int& n, int& type) {
	int i;
	for(i = STR_FIRST; i < STR_LAST; ++i) {
		if(settingTags[i] == name) {
			n = i;
			type = TYPE_STRING;
			return true;
		}
	}
	for(i = INT_FIRST; i < INT_LAST; ++i) {
		if(settingTags[i] == name) {
			n = i;
			type = TYPE_INT;
			return true;
		}
	}
	for(i = INT64_FIRST; i < INT64_LAST; ++i) {
		if(settingTags[i] == name) {
			n = i;
			type = TYPE_INT64;
			return true;
		}
	}
	return false;
}

/**
 * @file
 * $Id: SettingsManager.cpp Last changed: 2005-07-15 14:17:57 By: Pothead for SVN: 250 Exp$ */
